package com.kamistoat.netty.zercopy_new;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 使用NIO零拷贝传输文件
 */
public class NewIOServer {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7001);
        try {
            // 直连通信，不设置Selector了，ServerSocketChannel直接绑定监听端口
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(inetSocketAddress);
            ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

            while (true) {
                int readCount = 0;
                // 等待连接，当有新连接时直接分配一个SocketChannel
                SocketChannel socketChannel = serverSocketChannel.accept();
                // 获取到新连接，开始接收数据
                while (readCount != -1) {
                    try {
                        readCount = socketChannel.read(byteBuffer);
                        // buffer不能像byte[]那样直接复用。
                        // 如果下次直接接着用buffer读，当buffer空间满了之后将会陷入死循环，因为每次尝试从SocketChannel中读取0字节的数据，必然每次都成功
                        // 使用rewind()将buffer复位
                        byteBuffer.rewind();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
